# -*- coding: utf-8 -*-
'''
Created on 07-10-2012

@author: LONG HOANG GIANG
'''
from Cheetah.Template import Template
from cherrypy.lib.static import serve_file
import cherrypy
import datetime
import os
import re
import sys
import traceback
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from CrawlerLib2 import commonlib, html2text
from Model.storymodelv3 import StoryModel
from category import Category

# -----------------------------------------
# DEFINE CONSTANT
# -----------------------------------------
ROOT = os.path.dirname(__file__)
DS = '/'
CONFIG_FILE = os.path.join(ROOT, 'app.cfg')


# -----------------------------------------
# Web service
# -----------------------------------------

session = {'database': ''}

class EditorWebservices():
    
    _config_file = '/longhoanggiang/tmp/webservice_session'
    _cp_config = {'tools.staticdir.on': True,
                  'tools.gzip.on': True,
                  #'tools.staticdir.dir': os.path.join(ROOT, 'files'),
                  #'tools.staticdir.index': 'index.html',
    }
    
    def restart_session(self):
        global session
        ss = commonlib.pickle_load(self._config_file)
        if ss != None: session = ss
        
    def check_session_loaded(self):
        if session['database'] == '':
            self.restart_session()
    
    @cherrypy.expose
    def index(self, **request):
        global session
        action = request.get('action', '')
        if session['database'] == '':
            ss = commonlib.pickle_load(self._config_file)
            if ss is None: ss = session
            session = ss
        data = {'action': '/insert', 'database': session['database'], 'year': datetime.date.today().year, 
                'chapterTitle': '', 'chapterContent': '', 'chapters': []}
        database = session['database']
        storyModel = StoryModel(database)
        storyModel.open()
        categories = storyModel.get_all_categories()
        if os.path.isfile(database):
            data['chapters'] = storyModel.get_story_title()
            if action == 'edit':
                sid = request.get('id', -1)
                chapter = storyModel.get_story_by_id(sid)
                if chapter is not None:
                    data['chapterTitle'] = chapter[2]
                    data['chapterContent'] = chapter[3]
                    data['action'] = '/save?cid={0}&id={1}'.format(chapter[1], chapter[0])
                    data['deleteAction'] = '/delete-item?cid={0}&id={1}'.format(chapter[1], chapter[0])
        storyModel.close()
        t = Template(file="templates/index.tpl", searchList={'database': session['database'], 'categories': categories, 'data': data, 'action': action}).respond()
        return t
        
    @cherrypy.expose
    def insert(self, chapter, content, database, **kwargs):
        if session['database'] != database:
            session['database'] = database
            commonlib.pickle_dump(session, self._config_file)
        if not os.path.isfile(database):
            self.create_database(database)
        download_image = kwargs.get('turnondownload', False)
        base_url = kwargs.get('baseUrl', '')
        catid = kwargs.get('catid', 0)
        content = commonlib.convertHTMLEntitiesToUnicode(content)
        if download_image:
            content = html2text.html2text(content, baseurl=base_url, download=commonlib.downloadImage, path=os.path.join(ROOT, 'downloaded'))
        else:
            content = html2text.html2text(content, baseurl=base_url)
        content = re.sub(r"\n\s*\n\s*\n\s*\n", "\n\n", content)
        content = re.sub(r"\n", " <br />", content)
        success, msg = True, ''
        if chapter.strip() == '' or content.strip() == '': raise cherrypy.HTTPRedirect("/index?msg=error")
        try:
            db = StoryModel(session['database'])
            db.open()
            chapter = commonlib.toUpper(chapter)
            db.add_story(chapter, content, catid)
            db.close()
        except:
            success = False
            traceback.print_exc()
        raise cherrypy.HTTPRedirect("/index?msg=success") if success else cherrypy.HTTPRedirect("/index?msg=failed")
    
    @cherrypy.expose
    def save(self, chapter, content, **kwargs):
        self.check_session_loaded()
        db = StoryModel(session['database'])
        db.open()
        cid = kwargs.get('cid', -1)
        id = kwargs.get('id', -1)
        success, msg = True, ''
        base_url = kwargs.get('baseUrl', '')
        content = commonlib.convertHTMLEntitiesToUnicode(content)
        download_image = kwargs.get('turnondownload', False)
        try:
            if download_image:
                content = html2text.html2text(content, baseurl=base_url, download=commonlib.downloadImage, path=os.path.join(ROOT, 'downloaded'))
            else:
                content = html2text.html2text(content, baseurl=base_url)
            content = re.sub(r"\n\s*\n\s*\n\s*\n", "\n\n", content)
            content = re.sub(r"\n", " <br />", content)
            chapter = commonlib.toUpper(chapter)
            db.upate_story(chapter, content, id)
        except:
            success = False
            msg = str(sys.exc_info()[1])
        finally:
            db.close()
        if success:
            raise cherrypy.HTTPRedirect("/index?msg=success")
        return msg
    
    @cherrypy.expose(alias = 'delete-item')
    def delete_item(self, cid, id, **kwargs):
        self.check_session_loaded()
        database = session['database']
        storyModel = StoryModel(database)
        storyModel.open()
        success, msg = True, ''
        try:
            storyModel.db.execute("DELETE FROM vn_gq_udv_story WHERE id={0}".format(id))
        except:
            msg = "Problem occurred when delete: {0}".format(sys.exc_info()[1])
        finally:
            storyModel.close()
        if success: raise cherrypy.HTTPRedirect("/index")
        return msg
    
    @cherrypy.expose(alias='load-database')
    def load_database(self, name):
        if session['database'] != name and name != '':
            session['database'] = name
            commonlib.pickle_dump(session, self._config_file)
        raise cherrypy.HTTPRedirect("/index")
    
    @cherrypy.expose(alias='new-database')
    def new_database(self, **request):
        tempDbPath = ROOT + '/files/story'
        if not os.path.isfile(tempDbPath):
            self.create_database(tempDbPath)
        serve_file(tempDbPath, "application/x-download", "attachment")

    def create_database(self, dbPath):
        if not os.path.exists(os.path.dirname(dbPath)): os.makedirs(os.path.dirname(dbPath), 0777)
        db = StoryModel(dbPath)
        db.open(True)
        db.close()
    
def startWebService():
    
    cherrypy.config.update({'server.socket_port':8888, 
        'server.socket_host':'0.0.0.0', 
        'engine.autoreload.on': True, 
        'tools.sessions.on': True,
        'tools.encode.encoding': 'utf-8',
        'server.environment': 'development', 
        'sessionFilter.on': True})
    
    conf = {'/images': {'tools.staticdir.on': True,
                       'tools.staticdir.dir': os.path.join(ROOT, 'images'),
                       'tools.staticdir.content_types': {'png': 'image/png',
                                                         'jpg': 'image/jpg',
                                                         'gif': 'image/gif'}},
            '/files': {'tools.staticdir.on': True,
                       'tools.staticdir.dir': os.path.join(ROOT, 'files')},
            '/css': {'tools.staticdir.on': True,
                     'tools.staticdir.dir': os.path.join(ROOT, 'css')},
            '/js': {'tools.staticdir.on': True,
                    'tools.staticdir.dir': os.path.join(ROOT, 'js')}}
    
    cherrypy.log.error_log.propagate = False
    cherrypy.log.access_log.propagate = False
    root = EditorWebservices()
    root.category = Category()
    cherrypy.quickstart(root, '/', config=CONFIG_FILE)

if __name__ == '__main__':
    
    startWebService()
    
